
package com.tenentia.pcmps.swm.web.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

/**
 * 
 * @author tEnEntia, S.L.N.E.
 * 
 */
public class FileDownloadServlet extends HttpServlet {

	/**
	 * Default serialVersionUID.
	 */
	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = Logger.getLogger(FileDownloadServlet.class.getPackage().getName());

	public static final String STRING_DOWNLOAD_FILE_ID = "DOWNLOAD_FILE_ID";

	public static final String STRING_DOWNLOAD_CONTENT_TYPE = "DOWNLOAD_CONTENT_TYPE";

	public static final String STRING_DOWNLOAD_CONTENT_DISPOSITION = "DOWNLOAD_CONTENT_DISPOSITION";

	public FileDownloadServlet() {

		super();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		InputStream inputStream = null;

		File file = null;

		try {

			file = new File(request.getParameter(STRING_DOWNLOAD_FILE_ID));

			String contentType = request.getParameter(STRING_DOWNLOAD_CONTENT_TYPE);
			String contentDisposition = request.getParameter(STRING_DOWNLOAD_CONTENT_DISPOSITION);

			response.setContentType(contentType);
			response.setHeader("Content-Disposition", contentDisposition);

			inputStream = new FileInputStream(file);

			IOUtils.copy(inputStream, response.getOutputStream());
		} catch (Exception e) {
			LOGGER.error(e, e);
		} finally {
			if (null != inputStream) {
				IOUtils.closeQuietly(inputStream);
			}
			if (null != file && file.exists()) {
				try {
					file.delete();
				} catch (Exception e2) {
					LOGGER.error("Unable to delete file: " + file.getAbsolutePath());
				}
			}
		}
	}

}
